package exception

import (
	"fmt"
	"net/http"
)

type ApiException struct {
	// 业务异常
	BizCode  int    `json:"biz_code"`
	Message  string `json:"message"`
	Data     any    `json:"data"`
	HttpCode int    `json:"http_code"`
}

func NewNotFound(format string, a ...any) *ApiException {
	return NewError(5004, format, a...)
}

func NewAuthFound(format string, a ...any) *ApiException {
	return NewError(5000, format, a...)
}

func NewError(code int, text string, a ...any) *ApiException {
	HttpCode := http.StatusInternalServerError
	// 0 ~ 5xx
	if code/100 < 6 && code/100 > 0 {
		HttpCode = code
	}

	return &ApiException{
		BizCode: code,
		Message: fmt.Sprintf(text, a...),
		// 如果是异常，直接使用http code作为异常, 不在使用200
		HttpCode: HttpCode,
	}
}

func (e *ApiException) Error() string {
	return e.Message
}

func IsNotFound(err error) bool {
	if e, ok := err.(*ApiException); ok {
		if e.BizCode == 5004 {
			return true
		}
	}

	return false
}

func IsNotFound1(err error) bool {
	if e, ok := err.(*ApiException); ok {
		if e.BizCode == 5000 {
			return false
		}
	}

	return true
}
